//
//  UploadVideoViewController.swift
//  HoneyBee
//
//  Created by Smith_Yang on 2018/6/14.
//  Copyright © 2018 point. All rights reserved.
//

import UIKit
import MobileCoreServices
import SwiftyJSON
import AVFoundation
import Photos


class UploadVideoViewController: BaseViewController {
    @IBOutlet weak var videobg: UIView!
    @IBOutlet weak var videoImg: UIImageView!
    @IBOutlet weak var inputBg: UIView!
    @IBOutlet weak var titleTextField: UITextField!
    
    @IBOutlet weak var confirmBtn: UIButton!
    
    @IBOutlet weak var selectGroupButton: UIButton!
    
    @IBOutlet weak var descriptionTextview: UITextView!
    var selectedGroupMode: TopicGroupModel?
    
    var imagePickInfo:[UIImagePickerController.InfoKey : Any] =  [UIImagePickerController.InfoKey : Any]()
    var currentVideoSize:Int64 = 0
    var currentVideoTime:Int = 0
    
    var type:Int = 0 //0图片 1视频
    
    lazy var progressView = UIProgressView()
    
    fileprivate var imageSize:CGSize =  CGSize()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "添加视频"

        let playImg = UIImage.icon(from: kIcon_play, color: UIColor(hex: "#5FD8A3")!, imageSize: CGSize(width: 48, height: 48)).withRenderingMode(.alwaysOriginal)
        videoImg.image = playImg
        
        videobg.layer.cornerRadius = 3
        inputBg.layer.cornerRadius = 3
        
        titleTextField.layer.cornerRadius = titleTextField.frame.size.height/2.0
        confirmBtn.layer.cornerRadius = confirmBtn.frame.size.height/2.0
        let shadowLayer0 = CALayer()
        shadowLayer0.frame = confirmBtn.bounds
        shadowLayer0.shadowColor = UIColor(red: 17.0 / 255.0, green: 114.0 / 255.0, blue: 153.0 / 255.0, alpha: 0.21).cgColor
        shadowLayer0.shadowOpacity = 1
        shadowLayer0.shadowOffset = CGSize(width: 0, height: 1)
        shadowLayer0.shadowRadius = 4
        let shadowSize0:CGFloat = 0
        let shadowSpreadRect0 = CGRect(x: -shadowSize0, y: -shadowSize0, width: confirmBtn.bounds.size.width+shadowSize0*2, height: confirmBtn.bounds.size.height+shadowSize0*2)
        let shadowSpreadRadius0 =  confirmBtn.layer.cornerRadius == 0 ? 0 : confirmBtn.layer.cornerRadius+shadowSize0;
        let shadowPath0 = UIBezierPath(roundedRect: shadowSpreadRect0, cornerRadius: shadowSpreadRadius0)
        shadowLayer0.shadowPath = shadowPath0.cgPath
        confirmBtn.layer.addSublayer(shadowLayer0)
        
        videobg.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(addVideoAction))
        videobg.addGestureRecognizer(tapGesture)
        
        view.addSubview(progressView)
        progressView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(4)
        }
        progressView.backgroundColor = UIColor.blue
        progressView.progress = 0
        progressView.isHidden = true

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func selectGroupAction(_ sender: Any) {
        
        
        let selectGroupVC = GroupSelectionViewController();
        
        selectGroupVC.selectedGroup { (model) in
            self.selectedGroupMode = model
            
            self.selectGroupButton.setTitle(model.groupName, for: .normal)
            
        }
        
        self.navigationController?.pushViewController(selectGroupVC, animated: true)
        
    }
    
    @objc func addVideoAction(){
        
        clickUpBtn();
    }
}


extension UploadVideoViewController {
    
    @IBAction func submitAction(_ sender: Any) {
        var data:Data = Data() //UIImagePickerController.InfoKey UIImagePickerControllerMediaURL
        let url = imagePickInfo[UIImagePickerController.InfoKey.mediaURL] as! URL
        let asset = AVURLAsset(url:url)
        let time: CMTime = asset.duration
        let s = CMTimeGetSeconds(time)
        if s  >= 15 * 60 {
            hudLoadMessage("不得大于15分钟")
            return
        }else if s < 9{
            hudLoadMessage("不得小于10秒")
            return
        }
        data = try! Data.init(contentsOf: url)
        currentVideoSize = Int64(data.count)
        currentVideoTime = lroundf(Float(s))
        
        self.progressView.isHidden = false
        let uploadOptionVideo = QNUploadOption.init(mime: "video/mp4", progressHandler: { [weak self](key, percent:Float) in
            DispatchQueue.main.async(execute: {
                self?.progressView.progress = percent
            })
            }, params: nil, checkCrc: false, cancellationSignal: nil)
        
        
        self.hudLoad()
        TempNetTool.get(kHost + kgetImgToken, parameters: ["timestamp":"11","sign":"22"], progress: nil, success: { [weak self](result) in
            let json = JSON(result ?? "")
            let token = json["uptoken"].string
            let uploadManage = QNUploadManager.init()
            
            uploadManage?.put(data, key: nil, token: token, complete: { [weak self] (info, key, result) in
                
                let json = JSON(result as Any)
                let url = json["key"].stringValue
                self?.upload(path: kqnVideoHost + url)
                self?.progressView.isHidden = true
                }, option: uploadOptionVideo)
            
        }) { [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
        }
    }
    
    
    fileprivate func upload(path:String) {
        
        
//        guard let title = titleTextFiled.text else {
//            hudLoadMessage("请输入文章名称。")
//            return
//        }
//
//        guard let groupId = selectedGroupMode?.id else {
//            hudLoadMessage("请选择发表文章的小组。")
//            return
//        }
//
//        guard topicDetailTextView.contentHTML.count > 0  else {
//            hudLoadMessage("请输入文章内容。")
//            return
//        }
//
        let videoPath = path
        let videoImage = path + "?vframe/jpg/offset/1"
        
        let current = String().currentTime()
        let dict = [
            "authorId": UserInfo.shareInstance.userModel().id,
            "groupId": selectedGroupMode?.id ?? 0,
            "videoSize": currentVideoSize,
            "videoTime": currentVideoTime,
            "remark": descriptionTextview.text,
            "resource": videoPath,
            "videoImgPath":videoImage,
            "type": "01",
            "title": titleTextField.text! ] as [String : Any]
        let api = kHost + kaddNewTopicList + "".apiF(time: current, sign: "")
        self.hudLoad()
        TempNetTool.post(api, parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.hudHide()

            self?.navigationController?.popViewController(animated: true)
        }) {  [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
        }
        
    }
    
    
    func clickUpBtn() {
        if (self.titleTextField.text?.count)! <= 0 {
            self.hudLoadMessage("请先输入标题吧")
            return
        }
        photoClick()
    }
}

extension UploadVideoViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func photoClick() {
        
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary)  {
            self.hudLoadMessage("请检查相册权限")
            return
        }
        let photoVc = UIImagePickerController()
        photoVc.sourceType = .photoLibrary
        photoVc.mediaTypes =  [kUTTypeMovie as String]
        photoVc.delegate = self
        present(photoVc, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated:true, completion:nil)
        imagePickInfo = info
        
        if self.type == 0 {
            //self.addVideoView.titleLabel.text = "图片成功选择 👇上传"
        }else {
            //self.addVideoView.titleLabel.text = "视频成功选择 👇上传"
        }
    }
    
    /*
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        picker.dismiss(animated:true, completion:nil)
        imagePickInfo = info
        
        if self.type == 0 {
//            self.addVideoView.titleLabel.text = "图片成功选择 👇上传"
        }else {
//            self.addVideoView.titleLabel.text = "视频成功选择 👇上传"
        }
        
    }
    */
}
